package com.toolset.Activity.ToolItemActivity;

import android.app.ProgressDialog;
import android.os.Looper;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.ObjectArrayCodec;
import com.alibaba.fastjson.serializer.StringCodec;
import com.toolset.Activity.BaseActivity;
import com.toolset.R;
import com.toolset.Util.ExpressUtil;
import com.toolset.Util.HttpUtil;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import okhttp3.Cookie;
import okhttp3.Headers;
import okhttp3.OkHttpClient;

/*
查询快递工具 需要网络  调用www.woyaocha.net的sdk
 */

public class QueryExpress extends BaseActivity {

    private EditText expressInputEdit;
    private EditText expressOutputEdit;
    private Button expressBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_query_express);

        //初始化事件
        initEven();

        //设置点击查询快递按钮
        expressBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                final String order = expressInputEdit.getText().toString();

                //检查字符串为都是数字
                if (checkDate(order)) {

                    //创建打开对话框
                    final ProgressDialog dialog = new ProgressDialog(QueryExpress.this);
                    dialog.setTitle("正在查询快递");
                    dialog.setMessage("查询中，请稍等~");
                    dialog.setCancelable(true);
                    dialog.show();


                    final StringBuffer sb = new StringBuffer();
                    //获取物流信息

                    //拼接单号
                    final String url = "https://sp0.baidu.com/9_Q4sjW91Qh3otqbppnN2DJv/pae/channel/data/asyncqury?cb=jQuery110204759692032715892_1499865778178&appid=4001&com=&nu="+order;


                    //网络请求开启子线程
                    Thread thread = new Thread() {
                        public void run() {

                            //设置Cookies
                            Headers headers = new Headers.Builder()
                                    .add("Cookie","BAIDUID=CC44612E7DB0DBA6C4FB79A654956F99:FG=1; BIDUPSID=CC44612E7DB0DBA6C4FB79A654956F99; PSTM=1560262071; BDORZ=B490B5EBF6F3CD402E515D22BCDA1598; H_PS_PSSID=1431_21122_18560_29238_28518_29098_29368_28839_29221_26350; yjs_js_security_passport=8ce7268f321bc48f3b0a948d70d58b61665e29a3_1560584453_js")
                                    .build();

                            // 网络请求 获取结果 转化为中文
                            String result = unicodeDecode(HttpUtil.Get(url,headers));

                            //处理结果 去掉不符合json部分
                            result = result.substring(result.indexOf("(")+1,result.lastIndexOf(")"));

                            //解析为JSONObject
                            JSONObject jsonObject = JSON.parseObject(result);

                            System.out.println(jsonObject);

                            //获取json数据中的 status
                            int status =  jsonObject.getInteger("status");

                            if (status==0){

                    //获取data
                                Map<String ,Object> data = (Map<String, Object>) jsonObject.get("data");


                    //获取快递公式数据来源

                                //获取data --  company
                                Map<String ,Object> company = (Map<String, Object>) data.get("company");


                                //添加数据来源与公司
                                sb.append("\n " + "快递公司："+company.get("fullname")+"\n\n");

                    //获取快递公式数据来源 End



                    //获取快递时间 地址

                                //获取data -- info
                                Map<String ,Object> info = (Map<String, Object>) data.get("info");

                                //获取data -- info --context
                                List context = (List) info.get("context");




                                //遍历 context
                                for (int i =0;i<context.size();i++){
                                    //获取context中的list
                                    Map<String,Object> contextInfo = (Map<String, Object>) context.get(i);

                                    ///获取list中的time
                                    String time = dateToStamp((String) contextInfo.get("time"));

                                    ///获取list中的desc
                                    String desc = (String) contextInfo.get("desc");

                                    ///插入 time desc
                                    sb.append(time + "\n" + desc + "\n\n");

                                }

                    //获取快递时间 地址 end

                                //切换主线程添加文本
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        //如果长度不为0代表有结果
                                        if (sb.length()!=0) {
                                            expressOutputEdit.setText(sb.toString());
                                        }else{
                                            expressOutputEdit.setText("请检查快递单号是否正确！");
                                        }
                                        //关闭对话框
                                        dialog.dismiss();
                                    }
                                });


                            }

                        }
                    };
                    //启动线程
                    thread.start();


                } else {
                    Toast.makeText(QueryExpress.this, "请先检查快递单号是否正确再查询快递！", Toast.LENGTH_SHORT).show();
                }

            }
        });
    }

    private void initEven() {
        expressInputEdit = (EditText) findViewById(R.id.ExpressInputEdit);
        expressOutputEdit = (EditText) (EditText) findViewById(R.id.ExpressOutputEdit);
        expressBtn = (Button) findViewById(R.id.ExpressBtn);
    }

    //检查数据  判断字符串是不是为数字
    private boolean checkDate(String str) {
        char chars[] = str.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            if (!Character.isDigit(chars[i])) {
                return false;
            }
        }
        return true;
    }

    //unicode 解析 中文
    public static String unicodeDecode(String string) {
        Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{4}))");
        Matcher matcher = pattern.matcher(string);
        char ch;
        while (matcher.find()) {
            ch = (char) Integer.parseInt(matcher.group(2), 16);
            string = string.replace(matcher.group(1), ch + "");
        }
        return string;
    }

    /*
     * 将时间转换为时间戳
     */
    public  String dateToStamp(String stamp)  {
        Long timestamp = Long.parseLong(stamp);
        String date = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new Date(timestamp * 1000));
        return date;
    }

}
